using System;
using System.IO;
using Canlipe.ServiceInterfaces;
using System.Globalization;
using Canlipe.Utils;

namespace Canlipe.Lib
{
	/* Ok, so the format of the file we have is:
	 * 
	 * Title: blabla
	 * Date: 2012-10-31
	 * 
     * Content:
	 * [content]
	 * 
	 * */
	public class Post
	{
		#region Static members

        public static Post FromPath(string path, ILogger logger, IContentParser contentParser)
		{
			return Post.FromString (File.ReadAllText (path), logger, contentParser);
		}

        public static Post FromString(string text, ILogger logger, IContentParser contentParser)
		{
			Post post = new Post ();
			var pcs = text.Split (new [] { "Content:" }, 2, StringSplitOptions.None);
			if (pcs.Length != 2) {
				logger.Log ("Failed parsing post - no header separator");
			}
			var headerText = pcs [0].Trim (new [] { ' ', '\n' });

            post.Content = contentParser.Parse(pcs[1].Trim(new[] { ' ', '\n' }));

			var headers = headerText.Split (new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (var header in headers) {
				var headerPcs = header.Trim ().Split (new [] { ':' }, 2, StringSplitOptions.None);
				if (headerPcs.Length != 2) {
					logger.Log (string.Format ("Check header in `{0}` - some errors there", header));
					continue;
				}

				headerPcs [0] = headerPcs [0].Trim ();
				headerPcs [1] = headerPcs [1].Trim ();

				switch (headerPcs [0]) {
				case "Title":
					post.Title = headerPcs [1];
					break;
				case "Date":
					try {
						post.Date = DateTime.ParseExact (headerPcs [1], "yyyy-MM-dd", CultureInfo.InvariantCulture);
					} catch {
						logger.Log (
							"Failed parsing date; date format should be yyyy-MM-dd");
					}
					break;
				case "Slug":
					post.Slug = headerPcs [1];
					break;
				default:
					logger.Log (
						string.Format ("Unknown header: {0}", header));
					break;
				}
			}

			return post;
		}

		#endregion

		public Post ()
		{
			this.Title = string.Empty;
			this.Content = string.Empty;
		}

		public string Title { get; set; }

		public string Slug { get; set; }

		public string Content { get; set; }

		public DateTime Date { get; set; }

		public string Url { 
			get {
				return string.Format (
					"{0}/{1}/{2}.html",
					this.Date.Year,
					this.Date.Month,
					this.Slug);
			}
		}
	}
}

